package com.yzkj.cpjxc.business.framework.utils;

import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.system.exception.Message;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Json 工具类
 */
public class JsonUtils {

	public static void main(String[] args) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("isThroughCheck", "notThroughCheck");
		jsonMap.put(Constants.MESSAGE, new Message("title1", "content1", "www.baidu.com"));

		String result = JsonUtils.toJson(jsonMap);
		System.out.println(result);
	}

	/**
	 * 把对象转换成json对象
	 */
	public static String toJson(Object obj) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setVisibility(JsonMethod.GETTER, Visibility.ANY);
		mapper.setDateFormat(new SimpleDateFormat(DateTimeUtils.sdfyyyyMMddHHmmss));
		mapper.setSerializationInclusion(Inclusion.NON_NULL);
		String result = mapper.writeValueAsString(obj);
		return result;
	}

	/**
	 * 根据mapper把 对象转换成json对象
	 * <pre>
	 * mapper可以设置日期的格式，是否显示null值等
	 * </pre>
	 * @param obj 要转换成json的对象
	 * @param mapper 如果mapper为null,则调用默认的toJson方法，否则使用传进来的mapper生成
	 * @return
	 * @throws Exception
	 */
	public static String toJson(Object obj, ObjectMapper mapper) throws Exception {
		if (mapper == null) {
			return toJson(obj);
		} else {
			return mapper.writeValueAsString(obj);
		}
	}
	
	/**
	 * 把json数据转成对象
	 * @modifier:
	 * @modifiedDate:
	 * @param json
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> T json2obj(String json, Class<?> clz) throws Exception {
		ObjectMapper om = new ObjectMapper();
		om.setDateFormat(new SimpleDateFormat(DateTimeUtils.sdfyyyyMMddHHmmss));
		return (T) om.readValue(json, clz);
	}

	/**
	 * 通告response对象把传进来的参数对象转换成json对象，并写出去
	 * @modifier:
	 * @modifiedDate:
	 * @param response
	 * @param obj 要转换成json的对象
	 * @throws Exception
	 */
	public static void responseJson(HttpServletResponse response, Object obj) throws Exception {

		String result = toJson(obj);
		response.setContentType("text/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache"); // 取消浏览器缓存
		PrintWriter out = response.getWriter();
		out.print(result);
		// System.out.println(result);
		out.flush();
		out.close();
	}

	/**
	 * 通告response对象和指定的mapper,把传进来的参数对象转换成json对象，并写出去
	 * @modifier:
	 * @modifiedDate:
	 * @param response
	 * @param obj
	 * @param mapper
	 * @throws Exception
	 */
	public static void responseJson(HttpServletResponse response, Object obj, ObjectMapper mapper) throws Exception {
		
		String result = "";
		if (mapper == null) {
			result = toJson(obj);
		} else {
			result = toJson(obj, mapper);
		}

		response.setContentType("text/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache"); // 取消浏览器缓存
		PrintWriter out = response.getWriter();
		out.print(result);
		// System.out.println(result);
		out.flush();
		out.close();

	}

	/**
	 * 通告response对象把传进来的分页参数对象（pager）转换成json对象，并写出去
	 * @modifier:
	 * @modifiedDate:
	 * @param response
	 * @param pager 分页对象
	 * @throws Exception
	 */
	public static <T> void responsePageJson(HttpServletResponse response, Pager<T> pager) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 当前页
		jsonMap.put("currentPage", pager.getCurrentPage());
		// 总页数
		jsonMap.put("pageCount", pager.getTotalPage());
		// 总记录数
		jsonMap.put("rowCount", pager.getTotal());
		// 结果集
		jsonMap.put("dataList", pager.getDataList());
		
		//字典届数组别代码
		jsonMap.put("dicGroupType", pager.getDicGroupType());
		
		jsonMap.put("beginDateStr", pager.getBeginDateStr());
		jsonMap.put("endDateStr", pager.getEndDateStr());
		
		responseJson(response, jsonMap);
	}

	/**
	 * 通告response对象和指定的mapper,把传进来的分页参数对象（pager）转换成json对象，并写出去
	 * @modifier:
	 * @modifiedDate:
	 * @param response
	 * @param pager 分页对象
	 * @param mapper 如果mapper为null,则调用默认的responseJson方法，否则使用传进来的mapper生成
	 * @throws Exception
	 */
	public static <T> void responsePageJson(HttpServletResponse response, Pager<T> pager, ObjectMapper mapper) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 当前页
		jsonMap.put("currentPage", pager.getCurrentPage());
		// 总页数
		jsonMap.put("pageCount", pager.getTotalPage());
		// 总记录数
		jsonMap.put("rowCount", pager.getTotal());
		// 结果集
		jsonMap.put("dataList", pager.getDataList());

		if (mapper == null) {
			responseJson(response, jsonMap);
		} else {
			responseJson(response, jsonMap, mapper);
		}
	}

	/**
	 * TODO
	 * @modifier:
	 * @modifiedDate:
	 * @return
	 */
	public static ObjectMapper getDefaultMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setVisibility(JsonMethod.GETTER, Visibility.ANY);
		mapper.setDateFormat(new SimpleDateFormat(DateTimeUtils.sdfyyyyMMddHHmmss));
		mapper.setSerializationInclusion(Inclusion.NON_NULL);
		return mapper;
	}

	/**
	 * 通告response对象和指定的mapper,把传进来的分页参数对象（pager）转换成json对象，并写出去
	 * @modifier:
	 * @modifiedDate:
	 * @param response
	 * @param pager
	 * @param dateFormat
	 * @throws Exception
	 */
	public static <T> void responsePageJson(HttpServletResponse response, Pager<T> pager, String dateFormat) throws Exception {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 当前页
		jsonMap.put("currentPage", pager.getCurrentPage());
		// 总页数
		jsonMap.put("pageCount", pager.getTotalPage());
		// 总记录数
		jsonMap.put("rowCount", pager.getTotal());
		// 结果集
		jsonMap.put("dataList", pager.getDataList());

		if (StringUtils.isBlank(dateFormat)) {
			responseJson(response, jsonMap);
		} else {
			ObjectMapper mapper = getDefaultMapper();
			mapper.setDateFormat(new SimpleDateFormat(dateFormat));
			responseJson(response, jsonMap, mapper);
		}
	}

}
